package com.finalterm.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.finalterm.common.result.Result;
import com.finalterm.order.entity.CompensationTask;
import com.finalterm.order.mapper.CompensationTaskMapper;
import com.finalterm.order.service.CompensationTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 补偿任务管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/compensation")
@RequiredArgsConstructor
public class CompensationTaskController {
    
    private final CompensationTaskService compensationTaskService;
    private final CompensationTaskMapper compensationTaskMapper;
    
    /**
     * 查询补偿任务列表
     */
    @GetMapping("/tasks")
    public Result<Page<CompensationTask>> getTasks(@RequestParam(defaultValue = "1") int page,
                                                 @RequestParam(defaultValue = "10") int size,
                                                 @RequestParam(required = false) String status,
                                                 @RequestParam(required = false) String orderNo) {
        Page<CompensationTask> taskPage = new Page<>(page, size);
        LambdaQueryWrapper<CompensationTask> wrapper = new LambdaQueryWrapper<>();
        
        if (status != null && !status.trim().isEmpty()) {
            wrapper.eq(CompensationTask::getStatus, status);
        }
        if (orderNo != null && !orderNo.trim().isEmpty()) {
            wrapper.like(CompensationTask::getOrderNo, orderNo);
        }
        
        wrapper.orderByDesc(CompensationTask::getCreateTime);
        
        Page<CompensationTask> result = compensationTaskMapper.selectPage(taskPage, wrapper);
        return Result.success("查询成功", result);
    }
    
    /**
     * 手动触发补偿任务处理
     */
    @PostMapping("/process")
    public Result<String> processCompensationTasks() {
        try {
            compensationTaskService.processPendingTasks();
            return Result.success("补偿任务处理完成");
        } catch (Exception e) {
            log.error("手动触发补偿任务处理失败：{}", e.getMessage(), e);
            return Result.error("补偿任务处理失败：" + e.getMessage());
        }
    }
    
    /**
     * 手动重试指定的补偿任务
     */
    @PostMapping("/retry/{taskId}")
    public Result<String> retryTask(@PathVariable Long taskId) {
        try {
            CompensationTask task = compensationTaskMapper.selectById(taskId);
            if (task == null) {
                return Result.error("补偿任务不存在");
            }
            
            if (!"PENDING".equals(task.getStatus()) && !"FAILED".equals(task.getStatus())) {
                return Result.error("只能重试待处理或失败的任务");
            }
            
            // 重置任务状态为待处理
            if ("FAILED".equals(task.getStatus())) {
                task.setStatus("PENDING");
                task.setRetryCount(0);
                task.setNextRetryTime(java.time.LocalDateTime.now());
                compensationTaskMapper.updateById(task);
            }
            
            boolean success = compensationTaskService.executeTask(task);
            if (success) {
                compensationTaskService.updateTaskStatus(taskId, "SUCCESS", null);
                return Result.success("任务重试成功");
            } else {
                compensationTaskService.incrementRetryCount(taskId, "手动重试失败");
                return Result.error("任务重试失败");
            }
        } catch (Exception e) {
            log.error("手动重试补偿任务失败，任务ID：{}，异常：{}", taskId, e.getMessage(), e);
            return Result.error("任务重试失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取补偿任务统计信息
     */
    @GetMapping("/stats")
    public Result<Object> getTaskStats() {
        LambdaQueryWrapper<CompensationTask> wrapper = new LambdaQueryWrapper<>();
        
        // 统计各状态的任务数量
        wrapper.eq(CompensationTask::getStatus, "PENDING");
        long pendingCount = compensationTaskMapper.selectCount(wrapper);
        
        wrapper.clear();
        wrapper.eq(CompensationTask::getStatus, "SUCCESS");
        long successCount = compensationTaskMapper.selectCount(wrapper);
        
        wrapper.clear();
        wrapper.eq(CompensationTask::getStatus, "FAILED");
        long failedCount = compensationTaskMapper.selectCount(wrapper);
        
        java.util.Map<String, Object> stats = new java.util.HashMap<>();
        stats.put("pendingCount", pendingCount);
        stats.put("successCount", successCount);
        stats.put("failedCount", failedCount);
        stats.put("totalCount", pendingCount + successCount + failedCount);
        
        return Result.success("统计信息获取成功", stats);
    }
}
